package com.hfb.mashibing.alip8.juc.c020_01_interview;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.LockSupport;

/**
 * 面试题（淘宝？）
 * 实现一个容器，提供2个方法：add，size
 * 写2个线程，线程1添加10个袁术到容器中，
 * 线程2实现监控元数个数。当个数为5时线程2 提出提示并退出。
 *
 * 使用2对LockSupport 解决此问题
 */
public class T08_Semaphore {
    // volatile 使线程间可见
    volatile List lis = new ArrayList();

    static Thread t1, t2;

    public void add(Object o) {
        lis.add(o);
    }
    public int size() {
        return lis.size();
    }

    public static void main(String[] args) throws InterruptedException {
        T08_Semaphore o = new T08_Semaphore();

        Semaphore s = new Semaphore(1);

        t1 = new Thread(()->{
            System.out.println("t1 启动");
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            for (int i=0;i<5;i++) {
                o.add(new Object());
                System.out.println("add "+i);
            }
            System.out.println("够 5 了");
            s.release();
            try {
                s.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            for (int i = 5; i < 10; i++) {
                o.add(new Object());
                System.out.println("add "+i);
            }
            s.release();
            System.out.println("t1 结束🔚");
        }, "t1");

        t2 = new Thread(()->{
            System.out.println("t2 启动");
            try {
                s.acquire();// t2 阻塞
                System.out.println("t2 结束🔚 ");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2");
        t1.start();
        t2.start();


    }
}
